import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/entity/lz_text.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/modle/main/bloc/details_bloc.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/clipboard_tool.dart';
import 'package:shopping_group/utils/image_utils.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/utils.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'details_to_paly_page.dart';
import 'package:bot_toast/bot_toast.dart';

class DetailsPage extends StatefulWidget {
  final String id;
  DetailsPage({Key key, @required this.id}) : super(key: key);
  @override
  _DetailsPageState createState() => _DetailsPageState();
}

class _DetailsPageState extends State<DetailsPage> {
  TextEditingController _controllerSignup = TextEditingController();
  CommoSpec4AppRecordEntity _entity = CommoSpec4AppRecordEntity();
  DetailsBloc _bloc;
  List<String> _imageList = [];
  StreamSubscription _imageSubscription;
  @override
  void initState() {
    super.initState();
    _bloc = DetailsBloc();
    _bloc.initDate.add(this.widget.id);
    _imageList..add('images/picture_loading.png');
    _imageSubscription = eventBus.on<DetailsImageUrlEvent>().listen((event) {
      if (null != event && !ObjectUtil.isEmptyList(event.lstImgUrl)) {
        setState(() {
          _imageList?.clear();
          _imageList = event.lstImgUrl;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (() {
        FocusScope.of(context).requestFocus(FocusNode());
      }),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: SingleChildScrollView(
            child: Stack(
          children: [
            _detailsView(),
            _showBlackView(),
          ],
        )),
        bottomNavigationBar: _bottomView(),

        //  Container(
        //   height: double.infinity,
        //   decoration: new BoxDecoration(
        //     color: Colours.title_white,
        //   ),
        //   child: _columnView(),
        // ),
      ),
    );
  }

  Widget _detailsView() {
    return SingleChildScrollView(
        scrollDirection: Axis.vertical,
        reverse: false,
        padding: EdgeInsets.all(0.0),
        physics: BouncingScrollPhysics(),
        child: Column(
          children: <Widget>[
            _swiperView(),
            _mainView(),
          ],
        ));
  }

  Widget _mainView() {
    return StreamBuilder(
      stream: _bloc.sendData,
      initialData: _entity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is CommoSpec4AppRecordEntity) {
          _entity = object;
        }
        if (ObjectUtil.isEmptyList(_entity.lstImgUrl)) {
          _entity.lstImgUrl = [];
        }
        if (ObjectUtil.isEmptyList(_entity.lstRemarkImgUrl)) {
          _entity.lstRemarkImgUrl = [];
        }
        return Column(
          children: <Widget>[
            _titleView(),
            WidgetUtils.drawCodeDivider(height: 3),
            _showInfoView(),
            SizedBox(
              height: 8,
            ),
            _imageView(),
          ],
        );
      },
    );
  }

  Widget _imageView() {
    return Column(
      children: _entity.lstRemarkImgUrl.map((String path) {
        return ImageUtils.fadeInImageNetwork(path);
      }).toList(),
    );
  }

  Widget _bottomView() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.only(top: 4),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () {
                String data = Apis.WEB_URL +
                    '?id=' +
                    this.widget.id +
                    '&phone=' +
                    BaseConstant.code;
                ClipboardTool.setDataToast(data);
                showUrLink(
                    '  一、已将此商品链接复制到您的剪贴板，可在社交工具软件直接粘贴链接并发送给您的朋友，请注意：一定要告知您的朋友不建议用微信自带的浏览器打开链接。\n' +
                        '  二、您也可以采用浏览器自带的分享功能进行分享，通常的操作步骤是：点击界面右上角的省略号->分享...->发送给朋友->选择微信好友或朋友圈，不同的浏览器操作上略有不同。');
              },
              child: Container(
                alignment: FractionalOffset.center,
                height: 42,
                child: WidgetUtils.getTextColorView(
                    '分享', Colors.white, Dimens.FONT_SIZE_13),
                decoration: BoxDecoration(
                  // borderRadius: BorderRadius.circular(10),
                  color: Colours.blackground_black_239,
                ),
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () {
                if (BaseConstant.isLogin) {
                  // if (!BaseConstant.isRealNameAuthen) {
                  //   BotToast.showText(text: '请先实名认证');
                  //   return;
                  // }
                  RouteUtil.goParameter(DetailsToPalyPage(entity: _entity));
                } else {
                  if (Utils.isWeixin()) {
                    BotToast.showText(text: '请重新打开链接，自动登录');
                  } else {
                    RouteUtil.goView(PageConstance.LOGIN_PAGE);
                  }
                }
              },
              child: Container(
                alignment: FractionalOffset.center,
                height: 42,
                child: WidgetUtils.getTextColorView(
                    '立即购买', Colors.white, Dimens.FONT_SIZE_13),
                decoration: BoxDecoration(
                  // borderRadius: BorderRadius.circular(10),
                  color: Colours.themeColor,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> showUrLink(data) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return AlertDialog(
          title: WidgetUtils.getTextColorView(
              '提示', Colors.black, Dimens.FONT_SIZE_18),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                // WidgetUtils.getTextColorView(
                //     '复制链接成功!请告知朋友浏览器打开', Colors.black, Dimens.FONT_SIZE_16),
                WidgetUtils.getTextColorView(
                    data, Colors.black, Dimens.FONT_SIZE_16),
              ],
            ),
          ),
          actions: <Widget>[
            // FlatButton(
            //   child: Text('取消'),
            //   onPressed: () {
            //     Navigator.of(context).pop();
            //   },
            // ),
            FlatButton(
              child: Text('确认'),
              onPressed: () => {Navigator.of(context).pop()},
            ),
          ],
        );
      },
    );
  }

  Widget _showInfoView() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          child: WidgetUtils.getTextColorView(
              '【${_entity.typeName}专区】${_entity.name}',
              Colours.text_2222,
              Dimens.FONT_SIZE_13),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: WidgetUtils.getTextColorView(
              '生鲜产品不支持拒收，如有破损联系客服秒赔付', Colours.text_91, Dimens.FONT_SIZE_13),
        ),
        SizedBox(
          height: 8,
        ),
        WidgetUtils.drawCodeDivider(height: 8),
        Container(
            padding: const EdgeInsets.symmetric(vertical: 24, horizontal: 8),
            child: Row(
              children: <Widget>[
                Expanded(
                    child: LzText(
                  _entity.giftRemark ?? "",
                  color: Colours.text_91,
                  fontSize: Dimens.FONT_SIZE_13,
                  maxLines: 10,
                )),

                // WidgetUtils.getTextColorView(
                //   '活动积分',
                //   Colours.text_91,
                //   Dimens.FONT_SIZE_13,
                // ),
                // SizedBox(
                //   width: 8,
                // ),
                // WidgetUtils.showBoxBotton('返还积分',
                //     borderColor: Colours.themeColor,
                //     textColor: Colours.themeColor,
                //     textSize: Dimens.FONT_SIZE_12,
                //     textPadding: 0),
                // SizedBox(
                //   width: 8,
                // ),
                // WidgetUtils.getTextColorView(
                //   _entity.giftRemark,
                //   Colours.text_91,
                //   Dimens.FONT_SIZE_13,
                //   maxLines: 10,
                // ),
              ],
            )),
        // WidgetUtils.drawCodeDivider(height: 8),
        // WidgetUtils.itmeStyleView('已选', '1件',
        //     textSize: Dimens.FONT_SIZE_13,
        //     textColor: Colours.text_91,
        //     isExpanded: false,
        //     bewteenleft: 8,
        //     verticalPadding: 16),
        WidgetUtils.drawCodeDivider(height: 10),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            WidgetUtils.itmeStyleView('运费', '包邮（若有退换货情况发生，邮费将由用户自理）',
                textSize: Dimens.FONT_SIZE_13,
                textColor: Colours.text_91,
                isExpanded: false,
                bewteenleft: 8,
                verticalPadding: 16),
            Padding(
              padding: EdgeInsets.only(left: 80),
              child: WidgetUtils.getTextColorView(
                '农副产品请当面签收，如遇损坏可要求退回',
                Colours.themeColor,
                Dimens.FONT_SIZE_13,
              ),
            ),
          ],
        ),
        SizedBox(
          height: 16,
        ),
        WidgetUtils.drawCodeDivider(height: 8),
      ],
    );
  }

  String _getType() {
    String type = '49';
    if (!ObjectUtil.isEmptyString(_entity.typeName)) {
      return _entity.typeName;
    }

    List<String> list = _entity.type.split('_');
    if (ObjectUtil.isEmptyList(list) || 1 == list.length) {
      return type;
    }

    return list[1];
  }

  Widget _titleView() {
    return Container(
      margin: const EdgeInsets.only(top: 4),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 0),
            child: Row(
              children: <Widget>[
                WidgetUtils.getTextColorView('¥${_entity.outPrice}',
                    Colours.themeColor, Dimens.FONT_SIZE_22),
                SizedBox(
                  width: 4,
                ),
                WidgetUtils.getTextColorView(
                    '¥${_entity.inPrice}', Colours.gray_99, Dimens.FONT_SIZE_16,
                    decoration: TextDecoration.lineThrough,
                    decorationColor: Colours.gray_66),
                Expanded(child: Container()),
                WidgetUtils.getTextColorView('已下单${_entity.hadShopCt}件',
                    Colours.gray_66, Dimens.FONT_SIZE_14),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _swiperView() {
    return Container(
        padding: const EdgeInsets.only(top: 0, left: 0, right: 0),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height / 3 + 64,
        child: Swiper(
          itemBuilder: _swiperBuilderOne,
          itemCount: _imageList.length,
          pagination: SwiperPagination(
              builder: DotSwiperPaginationBuilder(
            color: Colors.black54,
            activeColor: Colors.white,
          )),
          // control: SwiperControl(),
          scrollDirection: Axis.horizontal,
          autoplay: true,
          onTap: (index) {},
        ));
  }

  Widget _swiperBuilderOne(BuildContext context, int index) {
    return FadeInImage.assetNetwork(
      image: _imageList[index],
      placeholder: 'images/picture_loading.png',
      fit: BoxFit.fill,
    );
  }

  Widget _showBlackView() {
    return GestureDetector(
      onTap: () {
        RouteUtil.closeView();
      },
      child: Container(
        width: 32,
        height: 32,
        margin: const EdgeInsets.symmetric(vertical: 32, horizontal: 16),
        decoration: BoxDecoration(
            border: Border.all(color: Colours.transparent_80, width: 1.0),
            borderRadius: BorderRadius.circular(60.0),
            color: Colours.transparent_80),
        child: Icon(
          Icons.arrow_back_ios,
          color: Colours.title_white,
          size: 16,
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controllerSignup?.clear();
    _imageSubscription?.cancel();
  }
}
